//
//  Kylin_tabBar.m
//  01-LotteryBaseFrame
//
//  Created by Kylin on 16/1/4.
//  Copyright © 2016年 kylin. All rights reserved.
//

#import "Kylin_tabBar.h"
#import "Kylin_tabBarButton.h"
@interface Kylin_tabBar()
@property (weak,nonatomic)UIButton *selectButton;
@end
@implementation Kylin_tabBar

- (void)setItems:(NSArray *)items{
    
    _items = items;
    
    for (UITabBarItem *item in items) {
        
        UIButton *button = [[Kylin_tabBarButton alloc]init];
        [self addSubview:button];
        
        // 根据模型设置按钮图片(必须选择是背景图片)
        [button setBackgroundImage:item.image forState:UIControlStateNormal];
        [button setBackgroundImage:item.selectedImage forState:UIControlStateSelected];
        
        // 监听按钮点击
        [button addTarget:self action:@selector(buttonOnClick:) forControlEvents:UIControlEventTouchDown];
    }
}


- (void)buttonOnClick:(UIButton *)button{
    
    
    // 取消上次选中的按钮
    self.selectButton.selected = NO;
    
    // 选中当前按钮
    button.selected = YES;
    
    // 记录当前选中
    self.selectButton = button;
    
    if ([self.delegate respondsToSelector:@selector(tabBar:index:)]) {
        
        // 通知代理选中的那一个按钮
        [self.delegate tabBar:self index:button.tag];
    }
}

- (void)layoutSubviews{
    
    [super layoutSubviews];
    
    CGFloat buttonX = 0;
    CGFloat buttonY = 0;
    CGFloat buttonW = self.frame.size.width / self.subviews.count;
    CGFloat buttonH = self.frame.size.height;
    
    int i = 0;
    
    for (UIButton *button in self.subviews) {
        // 每次X增加一个按钮的宽度
        buttonX = i * buttonW;
        
        // 设置按钮的tag
        button.tag = i;
        
        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
        
        if (i == 0) {
            // 默认选 择0
            button.selected = YES;
            
            self.selectButton = button;

        }
        
        i ++;
    }
    
}
@end
